<?php

class Candidate extends AppModel
{

	public $name = 'Candidate';

	public $displayField = 'name';

	protected $archived_statuses = array('Y', 'N');

	public $validate = array(
        'name' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'Candidate.name.required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'Candidate.name.required',
            ),
        ),
        'name_latin' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'Candidate.latin_name.required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'Candidate.latin_name.required',
            ),
        ),
        'surname' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'Candidate.surname.required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'Candidate.surname.required',
            ),
        ),
        'surname_latin' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'Candidate.surname.required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'Candidate.surname.required',
            ),
        ),
        'archive_date' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
        ),
        'candidate_group_id' => array(
            'create_first' => array(
                'on' => 'create',
                'required' => true,
                'allowEmpty' => false,
                'message' => 'required',
            ),
            'update_first' => array(
                'on' => 'update',
                'required' => false,
                'allowEmpty' => false,
                'message' => 'required',
            ),
        ),
	);

	public $belongsTo = array(
        'Education' => array('className' => 'Education'),
        'Region' => array('className' => 'Region'),
        'Age' => array('className' => 'Age'),
        'Position' => array('className' => 'Position'),
        'Seniority' => array('className' => 'Seniority'),
        'Client' => array('className' => 'Client'),
        'Group' => array('className' => 'CandidateGroup',
            'foreignKey' => 'candidate_group_id',
        ),
	);
	public $hasMany = array(
		   'Testings' => array('className' => 'Testing', 'dependent'=>true),
	);

    function allowName($data)
    {
        $this->rel();
        return ! is_array($this->find(array("`{$this->primaryKey}`" => "!=".intval($this->id), "`name`" => $data)));
    }

	function allowDelete($fields = null)
	{
        return false;
	}

	function allowUpdate($fields = null)
	{
        return true;
	}
	/**
	 * Возвращает true если прохождение инструмента $test_id разрешено кандидату $id
	 *
	 * @param int $id - id кандидата
	 * @param int $test_id - id теста
	 * @return unknown
	 */
	function isAllowTestFor($id, $test_id)
	{
	    $this->rel();
        $group_id = $this->field("candidate_group_id", array("`{$this->name}`.`{$this->primaryKey}`" => $id));
        return $this->Group->isAllowTestFor($group_id, $test_id, $id);
	}

	function getToolsFor($id)
	{
	    $this->rel('');
	    $data = $this->read(null, $id);
	    if (empty($data[$this->name]['client_id'])) {
	        return array();
	    }

	    $tools = $this->getModel('Client')->getToolsFor($data[$this->name]['client_id']);
        if (empty($tools)) {
            return array();
        }

        foreach ($tools as &$tool) {
            $tool['Test']['__allows']['apply'] = $this->isAllowTestFor($id, $tool['Test']['id']);
        }

        return $tools;
	}

	function getAppointedToolsFor($id)
	{
	    $this->rel('Group.Client');
	    $data = $this->read(null, $id);
	    if (empty($data['Group']['Client'])) {
	        return array();
	    }

	    $Testing =& $this->getModel('Testing'); /* @var $Testing Testing */
	    $Testing->rel('Test');
	    $conds = array();
	    $conds[]["`{$Testing->name}`.`candidate_id`"] = $id;
	    $conds[]["`{$Testing->name}`.`pass_status`"] = 'READY';
	    $order = array(
	    	"`Test`.`type` ASC",
	    	"`{$Testing->name}`.`date` ASC",
	    );
	    $tools = $Testing->findAll($conds, null, $order);
        if (empty($tools)) {
            return array();
        }
		foreach ($tools as &$tool) {
            $tool['Testing']['__allows']['cancel'] = $Testing->allowCancel($tool['Testing']);
        }

        return $tools;
	}

	function getInProgressToolsFor($id)
	{
	    $this->rel('Group.Client');
	    $data = $this->read(null, $id);
	    if (empty($data['Group']['Client'])) {
	        return array();
	    }

	    $Testing =& $this->getModel('Testing'); /* @var $Testing Testing */
	    $Testing->rel('Test');
	    $conds = array();
	    $conds[]["`{$Testing->name}`.`candidate_id`"] = $id;
	    $conds[]["`{$Testing->name}`.`pass_status`"] = 'IN_PROGRESS';
	    $order = array(
	    	"`Test`.`type` ASC",
	    	"`{$Testing->name}`.`date` ASC",
	    );
	    $tools = $Testing->findAll($conds, null, $order);
        if (empty($tools)) {
            return array();
        }
		foreach ($tools as &$tool) {
            $tool['Testing']['__allows']['cancel'] = $Testing->allowCancel($tool['Testing']);
        }
        return $tools;
	}

	function getCompletedToolsFor($id)
	{
	    $this->rel('Group.Client');
	    $data = $this->read(null, $id);
	    if (empty($data['Group']['Client'])) {
	        return array();
	    }

	    $Testing =& $this->getModel('Testing'); /* @var $Testing Testing */
	    $Testing->rel('Test');
	    $conds = array();
	    $conds[]["`{$Testing->name}`.`candidate_id`"] = $id;
	    $conds[]["`{$Testing->name}`.`pass_status`"] = 'PASSED';
	    $order = array(
	    	"`Test`.`type` ASC",
	    	"`{$Testing->name}`.`pass_date` ASC",
	    );
	    $tools = $Testing->findAll($conds, null, $order);
        if (empty($tools)) {
            return array();
        }

        return $tools;
	}

	function allowReporting($fields  = null)
	{
		if (! (Auth::o()->is('active') && (Auth::o()->is('admin') || Auth::o()->is('REPORTS')))) {
		    return false;
		}
	    if (!isset($fields)) {
	        return true;
	    }
		if (empty($fields[$this->primaryKey])) {
		    return null;
		}
		$id = $fields[$this->primaryKey];
		$model =& $this->getModel('Testing');
		$model->rel();
   	    return (bool)is_array($model->find(array('candidate_id' => $id, 'pass_status' => 'PASSED')) );
	}

	function allowToArchive($fields  = null)
	{
		if (! (Auth::o()->is('active') && (Auth::o()->is('admin') || Auth::o()->is('CANDIDATES')))) {
		    return false;
		}
		if (empty($fields['archived'])) {
		    return null;
		}
		return $fields['archived'] == 'N';
	}

	function allowFromArchive($fields  = null)
	{
		if (! (Auth::o()->is('active') && (Auth::o()->is('admin') || Auth::o()->is('ARCHIVE')))) {
		    return false;
		}
		if (empty($fields['archived'])) {
		    return null;
		}
		return $fields['archived'] == 'Y';
	}

	function allowAdmining($fields  = null)
	{
		if (! (Auth::o()->is('active') && (Auth::o()->is('admin') || Auth::o()->is('CANDIDATES')))) {
		    return false;
		}
	    return true;
	}

	function presentReporting($fields = null)
	{
	    if (!isset($fields)) {
	        return false;
	    }
		if (empty($fields[$this->primaryKey])) {
		    return null;
		}
		$id = $fields[$this->primaryKey];
        $this->Testings->rel('Reportings');
        $conds = array();
        $conds[]["`{$this->Testings->name}`.`candidate_id`"] = $id;
        $tmp = $this->Testings->findAll($conds);

        $reportings = false;
        if (!empty($tmp)) {
            foreach ($tmp as $item) {
                if (count($item['Reportings'])) {
                    $reportings = true;
                    break;
                }
            }
        }
   	    return $reportings;
	}

	function modifyRow(&$row, $primary)
	{
	    if ($primary) {
    	    if (isset($row[$this->primaryKey])) {
                $row['__allows']['view_reports'] = $this->presentReporting($row);
                $row['__allows']['update']       = $this->allowUpdate($row);
                $row['__allows']['delete']       = $this->allowDelete($row);
                $row['__allows']['reporting']    = $this->allowReporting($row);
                $row['__allows']['admining']     = $this->allowAdmining($row);
                $row['__allows']['to_archive']   = $this->allowToArchive($row);
                $row['__allows']['from_archive'] = $this->allowFromArchive($row);
    	    }
	    }
	}

	/**
	 * Кеширование client_id, для оптимизации.
	 */
	//////////////////////////////////////////////////////
	protected function get_client_id_by_candidate_group_id($candidate_group_id)
	{
	    if (is_null($candidate_group_id)) {
	        return null;
	    }
        $this->Group->rel();
        $candidate_group = $this->Group->read("`{$this->Group->name}`.`client_id`", $candidate_group_id);
        if (empty($candidate_group[$this->Group->name]['client_id'])) {
            throw new DBException();
        }

        return $candidate_group[$this->Group->name]['client_id'];
	}

	protected $_cache_client_id = null;

	protected function beforeChange_candidate_group_id($new, $old)
	{
        $old_client_id = $this->get_client_id_by_candidate_group_id($old);
        $new_client_id = $this->get_client_id_by_candidate_group_id($new);
        if ($old_client_id != $new_client_id) {
            return false;
        }

        return true;
	}

	function beforeSave()
	{
	    if (! $this->exists()) {
	        $candidate_group_id = isset($this->data[$this->name]['candidate_group_id']) ? $this->data[$this->name]['candidate_group_id'] : null;
            $this->data[$this->name]['client_id'] = $this->get_client_id_by_candidate_group_id($candidate_group_id);
            $this->data[$this->name]['created'] = date('Y-m-d H:i:s');
	    }

	    return parent::beforeSave();
	}
	//////////////////////////////////////////////////////

	function getArchivedStatuses()
	{
	    return $this->archived_statuses;
	}

	function getArchivedStatusesList()
	{
	    $result = array();
	    foreach ($this->archived_statuses as $v) {
	        $result[$v] = __d(null, 'flag_'.$v, true);
	    }

	    return $result;
	}
}

?>